<?php

class SmsCenterAction extends Action {
	
	 /**
     * 平台以及系统短信相关设置相关
     *@param string $accessKeyId:Access Key ID
     *@param string $accessKeySecret:Access Key Secret
     *@param array $signNameInfo:短信模板
     *@param string $templateCrRemind:短信剩余条数提醒
     *@param string $smsServiceType:使用短信服务类型（ali:阿里云短信服务，system：系统短信服务）
     *@param int $isPlatParameter:是否属于平台短信参数（0：不属于，1：属于）
     */
	public function setSmsParameter($accessKeyId='',$accessKeySecret='',$signNameInfo='',$surplusNumberRemind='',$smsServiceType='',$isPlatParameter=0){

		 /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        /**2.数据表模型*/
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['id'];
        Session::switchCustomer(0);
        $sms = M('customer_sms_setting');
        Session::switchCustomer($customerId);

        /**3.数据表模型*/
        //判断平台是否已经存在短信配置信息，有则更新，没有则创建
        $time =  date('Y-m-d H:i:s',time());
        $where_sms['cid'] = $customerId;
        $smsInfo = $sms->where($where_sms)->find();
        M()->startTrans();
        if ($smsInfo){
            $update_sms['accessKeyId'] = $accessKeyId;
            $update_sms['accessKeySecret'] = $accessKeySecret;
            $update_sms['surplusNumberRemind'] = $surplusNumberRemind;
            $update_sms['smsServiceType'] = $smsServiceType;
            $update_sms['isPlatParameter'] = $isPlatParameter;
            $update_sms['updateTime'] = $time;
            $update_result = $sms->where("cid=$customerId")->save($update_sms);
            /** 4.  判断编辑是否成功 */        
            if ($update_result !== false) {
                //日志添加
                if ($isPlatParameter == 1){
                    R('Log/add', array('platSmsCenter', module_id_platSmsCenter, '短信中心', op_update, $sms->getLastSql(), '修改平台阿里云短信参数'));
                    $setResult = $this->setTemplateInfo($signNameInfo,$isPlatParameter);
                    if ($setResult == false){
                        M()->rollback();
                        $return['code'] = 1;
                        $return['msg'] = '编辑失败请重试';
                        $return['data'] = [];
                        Output::instance()->object($return);
                    }
                }else{
                    if ($smsServiceType == 'ali'){
                        R('Log/add', array('smsCenter', module_id_smsCenter, '短信中心', op_update, $sms->getLastSql(), '配置阿里云短信服务相关参数'));
                        $setResult = $this->setTemplateInfo($signNameInfo);
                        if ($setResult == false){
                            M()->rollback();
                            $return['code'] = 1;
                            $return['msg'] = '编辑失败请重试';
                            $return['data'] = [];
                            Output::instance()->object($return);
                        }
                    } else if ($smsServiceType == 'system') {
                        R('Log/add', array('smsCenter', module_id_smsCenter, '短信中心', op_update, $sms->getLastSql(), '配置系统短信服务相关参数'));
                    }                    
                }
                M()->commit();
                $return['code'] = 0;
                $return['msg'] = '编辑成功';
                $return['data'] = [];
                Output::instance()->object($return);
            }else{
                M()->rollback();
                $return['code'] = 1;
                $return['msg'] = '编辑失败请重试';
                $return['data'] = [];
                Output::instance()->object($return);
            }
        }else{
            $add_sms['cid'] = $customerId;
            $add_sms['accessKeyId'] = $accessKeyId;
            $add_sms['accessKeySecret'] = $accessKeySecret;
            $add_sms['surplusNumberRemind'] = $surplusNumberRemind;
            $add_sms['smsServiceType'] = $smsServiceType;
            $add_sms['isPlatParameter'] = $isPlatParameter;
            $add_sms['createTime'] = $time;
            $add_sms['updateTime'] = $time;
            $add_result = $sms->add($add_sms); 
            /** 4.  判断添加是否成功 */
            if ($add_result !== false) {
                //日志添加
                if ($isPlatParameter == 1){
                    R('Log/add', array('platSmsCenter', module_id_platSmsCenter, '短信中心', op_add, $sms->getLastSql(), '添加平台阿里云短信参数'));
                    $setResult = $this->setTemplateInfo($signNameInfo,$isPlatParameter);
                    if ($setResult == false){
                        M()->rollback();
                        $return['code'] = 1;
                        $return['msg'] = '编辑失败请重试';
                        $return['data'] = [];
                        Output::instance()->object($return);
                    }
                }else{
                    if ($smsServiceType == 'ali'){
                        R('Log/add', array('smsCenter', module_id_smsCenter, '短信中心', op_add, $sms->getLastSql(), '开通阿里云短信服务'));
                        $setResult = $this->setTemplateInfo($signNameInfo);
                        if ($setResult == false){
                            M()->rollback();
                            $return['code'] = 1;
                            $return['msg'] = '编辑失败请重试';
                            $return['data'] = [];
                            Output::instance()->object($return);
                        }
                    }else if ($smsServiceType == 'system'){
                        R('Log/add', array('smsCenter', module_id_smsCenter, '短信中心', op_add, $sms->getLastSql(), '开通系统短信服务'));
                    }                    
                }
                M()->commit();
                $return['code'] = 0;
                $return['msg'] = '添加成功';
                $return['data'] = [];
                Output::instance()->object($return);
            }else{
                M()->rollback();
                $return['code'] = 1;
                $return['msg'] = '添加失败请重试';
                $return['data'] = [];
                Output::instance()->object($return);
            }
        }

	}

	public function  setTemplateInfo($signNameInfo,$isPlatParameter = 0){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $smsTemplate = M('sms_template');
        Session::switchCustomer($customerId);
        $signNameInfo = json_decode($signNameInfo,true);
        foreach ($signNameInfo as $key=>$value){
            $time = date('Y-m-d H:i:s', time());
            //首先判断数据库中是否存在此状态的模板,有的话就更改，没有的话就添加
            $where_template['cid'] = $customerId;
            $where_template['status'] = $key;
            $templateId = $smsTemplate->where($where_template)->getField('id');
            if ($templateId) {
                $update_template['signName'] =  $value['signName'];
                $update_template['templateCode'] =  $value['templateCode'];
                $update_template['isPlatParameter'] =  $isPlatParameter;
                $update_template['open'] = $value['open'];
                $update_template['status'] = $key;
                $update_template['updateTime'] = $time;
                $update_result = $smsTemplate->where("id=$templateId")->save($update_template);
                if ($update_result == false){
                    return false;
                }
            }else {
                $time = date('Y-m-d H:i:s', time());
                $add_template['cid'] =  $customerId;
                $add_template['isPlatParameter'] =  $isPlatParameter;
                $add_template['signName'] =  $value['signName'];
                $add_template['templateCode'] =  $value['templateCode'];
                $add_template['open'] = $value['open'];
                $add_template['status'] = $key;
                $add_template['createTime'] = $time;
                $add_template['updateTime'] = $time;
                $newId = $smsTemplate->add($add_template);
                if ($newId == false){
                    return false;
                }
            }
        }
        return true;
    }
     /**
     * 平台以及系统短信相关设置查询
     */
    public function getSmsInfo(){
         /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        /**2.数据表模型*/
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['id'];
        Session::switchCustomer(0);
        $smsTemplate = M('sms_template');
        $sms = M('customer_sms_setting');
        $super = M('customer_super_setting');
        Session::switchCustomer($customerId);

         /**3.数据查询*/
         //查询基本sms设置信息
        $smsInfo = $sms->where("cid=$customerId")->find();
        $smsInfo = empty($smsInfo)? [] : $smsInfo;
        //查询平台短信模板消息
        $smsInfo['templateInfo'] = $smsTemplate->where("cid=$customerId")->select();
        //查询此平台是否允许开启系统短信服务
        $smsInfo['allowSystemSms'] = $super->where("customerId=$customerId")->getField('allowSystemSms');
        $return['code'] = 0;
        $return['msg'] = '设置信息获取';
        $return['data'] = $smsInfo;
        Output::instance()->object($return);

    }
    /**
     * 使用系统用短信服务并开通此功能平台列表查询
     * @param string $search  搜索项
     * @param int $start  开始值
     * @param int $limit  偏移量
     */
    public function smsSystemList($search='',$start=0,$limit=10){
         /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        /**2.数据表模型*/
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['id'];
        Session::switchCustomer(0);
        $sms= M('customer_sms_setting');
        Session::switchCustomer($customerId);

         /**3.数据查询*/
        $where['super.allowSystemSms'] = 1;
        $where['sms.smsServiceType'] = 'system';
        $where['user.agent'] = 'business';
        $where['user.status'] = 'open';
        empty($search) ? '' : $where['user.loginName'] =array("LIKE","%$search%");
        $total = $sms
            ->alias('sms')
            ->join("wx_customer_super_setting as super on sms.cid=super.customerId")
            ->join("wx_customer_user as user on user.customerId=sms.cid")
            ->where($where)
            ->field("user.loginName,sms.cid,sms.totalSendNumber,sms.totalRechargeNumber,sms.surplusNumber")
            ->count();
        $total = empty($total) ? 0: $total;
        $systemList = $sms
            ->alias('sms')
            ->join("wx_customer_super_setting as super on sms.cid=super.customerId")
            ->join("wx_customer_user as user on user.customerId=sms.cid")
            ->where($where)
            ->field("user.loginName,sms.cid,sms.totalSendNumber,sms.totalRechargeNumber,sms.surplusNumber")
            ->limit($start,$limit)
            ->order('user.updateTime desc')
            ->select();
        $systemList = empty($systemList) ? []: $systemList;
        /** 4.  将查询记录进行返回 */
        $return['code'] = 0;
        $return['msg'] = '查询记录返回';
        $return['data'] = $systemList;
        $return['total'] = $total;
        Output::instance()->object($return);

    }

    /**
     * 平台进行短信充值
     * @param int $customerId   平台id
     * @param int $number   短信充值条数
     */
    public function rechargeSms($customerId,$number){
         /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        /**2.数据表模型*/
        $userId = Session::$user['id'];
        Session::switchCustomer(0);
        $recharge = M('sms_recharge_record');
        $sms = M('customer_sms_setting');
        $user = M('customer_user');
        Session::switchCustomer($customerId);

         /**3.数据添加*/
        $recharge->startTrans();
        //进行平台短信充值表的数据增加
        $time =  date('Y-m-d H:i:s',time());
        $add_recharge['cid'] = $customerId;
        $add_recharge['number'] = $number;
        $add_recharge['createTime'] = $time;
        $add_result = $recharge->add($add_recharge); 

        //进行充值总条数增加
        $smsInfo = $sms->field('totalRechargeNumber,surplusNumber')->where("cid=$customerId")->find();
        $save_data['totalRechargeNumber'] = $smsInfo['totalRechargeNumber'] + $number;
        $save_data['surplusNumber'] = $smsInfo['surplusNumber'] + $number;
        $save_data['updateTime'] = $time;
        $recharge_result = $sms->where("cid=$customerId")->save($save_data);

        /** 4.  判断充值是否成功 */
        if (($add_result !== false) && ($recharge_result !== false)){
            $recharge->commit();
            $where_user['customerId'] = $customerId;
            $where_user['agent'] = 'business';
            $where_user['status'] = 'open';
            $userName = $user->where($where_user)->getField('loginName');
            R('Log/add', array('platSmsCenter', module_id_platSmsCenter, '短信中心', op_add, $sms->getLastSql(), '为用户'.$userName.'充值短信'.$number.'条'));
            $return['code'] = 0;
            $return['msg'] = '充值成功';
            $return['data'] = [];
            Output::instance()->object($return);
        }else{
            $recharge->rollback();
            $return['code'] = 1;
            $return['msg'] = '充值失败请重试';
            $return['data'] = [];
            Output::instance()->object($return);
        }

    }

    /**
     * 平台充值记录查询
     * @param int $customerId 平台id
     * @param int $start  开始值
     * @param int $limit  偏移量
     */
    public function rechargeSmsRecord($customerId,$start=0,$limit=10){
         /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        /**2.数据表模型*/
        $cid = Session::$user['customerId'];
        $userId = Session::$user['id'];
        Session::switchCustomer(0);
        $recharge = M('sms_recharge_record');
        Session::switchCustomer($cid);

         /**3.数据查询*/
        $where['cid'] = $customerId;
        $total = $recharge->where($where)->count();
        $total = empty($total) ? 0: $total;
        $rechargeList = $recharge->where($where)->limit($start,$limit)->order('createTime desc')->select();
        $rechargeList = empty($rechargeList) ? []: $rechargeList;
        /** 4.  将查询记录进行返回 */
        $return['code'] = 0;
        $return['msg'] = '查询记录返回';
        $return['data'] = $rechargeList;
        $return['total'] = $total;
        Output::instance()->object($return);

    }

    /**
     * 用户短信列表查询
     * @param string $startTime  开始时间
     * @param string $endTime  结束时间
     * @param string $moduleId  模块id
     * @param int $start  开始值
     * @param int $limit  偏移量
     */
    public function recordListInfo($startTime='',$endTime='',$moduleId='',$start=0,$limit=10){
         /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        /**2.数据表模型*/
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['id'];
        Session::switchCustomer(0);
        $record= M('sms_send_record');
        Session::switchCustomer($customerId);

         /**3.数据查询*/
        if ($startTime != '' && $endTime != '') {
            $where['createTime'] = array(array('egt', $startTime), array('elt', date('Y-m-d', strtotime("$endTime +1 day"))));
        } else if ($startTime != '') {
            $where["createTime"] = array('egt', $startTime);
        } else if ($endTime != '') {
            $where["createTime"] = array('elt', date('Y-m-d', strtotime("$endTime +1 day")));
        }

        $where['cid'] = $customerId;
        empty($moduleId) ? '' : $where['moduleId'] = $moduleId;
        $total = $record->where($where)->count();
        $total = empty($total) ? 0: $total;
        $recordList = $record->where($where)->limit($start,$limit)->order('createTime desc')->select();
        $recordList = empty($recordList) ? []: $recordList;
        /** 4.  将查询记录进行返回 */
        $return['code'] = 0;
        $return['msg'] = '查询记录返回';
        $return['data'] = $recordList;
        $return['total'] = $total;
        Output::instance()->object($return);

    }

    //数据迁移
    public function codesmsDataMigration()
    {
        set_time_limit(0);
        Session::switchCustomer(0);
        $smsTemplate = M('sms_template');
        $smsSetting = M('customer_sms_setting');
        //取出所有之前设置的二维码相关设置数据库
        $where_setting['signName'] = array("EXP","is NOT NULL");
        $where_setting['templateCode'] = array("EXP","is NOT NULL");
        $smsSettingInfo = $smsSetting->field("cid,signName,templateCode,isPlatParameter")->where($where_setting)->select();
        //进行循环查询处理
        $time = date('Y-m-d H:i:s', time());
        foreach ($smsSettingInfo as $key => $value) {
            $add_template['cid'] =  $value['cid'];
            $add_template['isPlatParameter'] =  $value['isPlatParameter'];
            $add_template['signName'] =  $value['signName'];
            $add_template['templateCode'] =  $value['templateCode'];
            $add_template['open'] = 1;
            $add_template['status'] = 'code';
            $add_template['createTime'] = $time;
            $add_template['updateTimen'] = $time;
            $smsTemplate->add($add_template);
            echo $smsTemplate->getLastSql();
            echo '<br/>';
        }


    }
}